package common.handler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.wzd.springmvc.entity.UserEntity;


/**
 * 登陆拦截器
 * Created by LiuZongRui on 17/2/20.
 */
public class LoginInterceptor implements HandlerInterceptor {

    /**
     * 该方法将在Controller处理之前进行调用，return false则请求中止
     */
    public boolean preHandle(HttpServletRequest httpServletRequest,  HttpServletResponse httpServletResponse, Object o) throws Exception {
        // 获取请求的url
       String url = httpServletRequest.getRequestURI();
       if (url.contains("/login.do")) {
            // 登陆接口，放行
    	   System.out.println("触发拦截器");
           return true;
        } else {
            HttpSession session = httpServletRequest.getSession();
            UserEntity user = (UserEntity) session.getAttribute("user");
            if (user != null) {
                return true;
            }
        }
        // 不符合条件的跳转到登录界面
        // 客户端跳转
        String str = httpServletRequest.getServerName().toString()+String.valueOf(httpServletRequest.getServerPort())+
        			httpServletRequest.getContextPath()+"/login.html";
        httpServletResponse.sendRedirect("login.html");
        return false;
    }

    /**
     * Controller处理之后，ModelAndView返回之前调用这个方法
     */
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
    	System.out.println("Controller处理之后，ModelAndView返回之前调用这个方法");
    }

     /**
     * 在ModelAndView视图渲染之后调用这个方法，一般此方法用于清理资源
     */
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
    	System.out.println("在ModelAndView视图渲染之后调用这个方法，一般此方法用于清理资源");
    }
 }
